package com.chenyue.cm.api.goods;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chenyue.cm.auth.Login;
import com.chenyue.cm.auth.LoginUser;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.utils.StringUtils;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.user.domain.*;
import com.chenyue.cm.user.domain.vo.JdCollectSVo;
import com.chenyue.cm.user.domain.vo.JdGoodDetailVo;
import com.chenyue.cm.user.domain.vo.SkuVo;
import com.chenyue.cm.user.service.*;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


@Api(tags = "商品信息")
@RestController
@RequestMapping("/api/goods")
public class ApiGoodsController{

    @Resource
    private JdGoodsSpuService goodsSpuService;
    @Resource
    private JdGoodsInfoService mClassifyInfoService;
    @Resource
    private JdGoodsSkuService skuService;
    @Resource
    private JdOrderCommentService orderCommentService;
    @Resource
    private JdShoppingBannerService shoppingBannerService;
    @Resource
    private JdFreightTemplateService freightTemplateService;


    /**
     * 　* @description:  首頁查看banner
     * 　* @param
     * 　* @return
     * 　* @throws
     * 　* @author gyt
     * 　* @date 2022/3/22 15:00
     */
    @GetMapping("/ViewBanner")
    @ResponseBody
    @ApiOperation(value="首頁查看banner",notes="首頁查看banner")
    @ApiOperationSupport(order=4)
    @Log(value="首頁查看banner",type="1")
    public Success<Object> ViewBanner() {
        List<JdShoppingBanner> list = null;
        list = shoppingBannerService.lambdaQuery()
                .eq(JdShoppingBanner::getDeleteFlag, '0')
                .orderByDesc(JdShoppingBanner::getId)
                .list();
        return Success.success(list);
    }


    /**
     * 获取商品一级分类
     *
     * @author chenyue
     * @date 2020/4/20 11:30 上午
     */
    @GetMapping("/getGoodsCategoryInfo")
    @ApiOperation(value = "【G1001】商品分类", notes = "商品分类")
    @ApiOperationSupport(order = 1)
    //【pass】
    public Success<List<JdGoodsInfo>> getGoodsCategoryInfo() {
        List<JdGoodsInfo> templateContent = mClassifyInfoService.list(Wrappers.<JdGoodsInfo>lambdaQuery().orderByDesc(JdGoodsInfo::getCreateTime));
        return Success.success(templateContent);
    }

    /**
     * 获取首页商品列表
     * 【G1002】
     *
     * @author xiebo
     * @date 2020/4/21 5:05 下午
     */
    @Login
    @GetMapping("/getHomePageGoodsList")
    @ApiOperation(value = "【G1004】商品列表", notes = "商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页数", name = "page", dataType = "string", required = true),
            @ApiImplicitParam(value = "单页条数", name = "rows", dataType = "string", required = true),
            @ApiImplicitParam(value = "关键字查询", name = "keyWord", dataType = "string"),
            @ApiImplicitParam(value = "分类id", name = "classifyId", dataType = "string"),
    })
    @ApiOperationSupport(order = 4)
    @Log(value = "获取商品列表")
    //【pass】
    public Success<Page<List<JdCollectSVo>>> getHomePageGoodsList(
       String classifyId, String keyWord , @RequestParam(defaultValue = "1") Integer page,
       @RequestParam(defaultValue = "10") Integer rows) {

        Long count = goodsSpuService.getHomePageGoodsCount(classifyId,keyWord);
        Page<List<JdCollectSVo>> result = new Page<>(page, rows, count.intValue());
        List<JdCollectSVo> results = goodsSpuService.getHomePageGoodsList(classifyId,keyWord);
        result.setContent(results);
        System.out.println(result);
        return Success.success(result);
    }


    /**
     * 商品详情
     * 【G1003】
     *
     * @author xiebo
     * @date 2020/4/22 10:10 上午
     */
    @Login
    @GetMapping("/getGoodsDetailInfo")
    @ApiOperation(value = "【G1005】商品详情", notes = "商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id", name = "goodsId", dataType = "string", required = true),
    })
    @ApiOperationSupport(order = 5)
    public Success<JdGoodDetailVo> getGoodsDetailInfo(@ApiIgnore @LoginUser JdAppUser user,String goodsId) {
        JdGoodDetailVo vo = goodsSpuService.getGoodsDetail(goodsId);
        return Success.success(vo);
    }



    /**
     * 获取商品评价信息
     * 【G1004】
     *
     * @param request
     * @return
     */
    @Login
    @RequestMapping(value = "/getGoodCommentList", method = RequestMethod.GET)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id", name = "goodsId", dataType = "string", required = true),
            @ApiImplicitParam(value = "页码", name = "page", dataType = "int", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "int", required = true),
    })
    @ApiOperation(value = "【G1006】获取商品评价信息", notes = "获取商品评价信息")
    @ApiOperationSupport(order = 6)
    //【pass】
    public Success<Page<List<JdOrderComment>>> getGoodCommentList(@ApiIgnore @LoginUser JdAppUser user,String goodsId,
                                                                  @RequestParam(defaultValue = "1") Integer page,
                                                            @RequestParam(defaultValue = "10") Integer rows) {

        LambdaQueryWrapper<JdOrderComment> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(goodsId)){
            wrapper.eq(JdOrderComment::getGoodsId,goodsId);
        }
        wrapper.orderByDesc(JdOrderComment::getCreateTime);
        final int total = orderCommentService.count(wrapper);
        final Page<List<JdOrderComment>> result = new Page<>(page, rows, total);
        wrapper.last(result.convertPage());
        List<JdOrderComment> list = orderCommentService.list(wrapper);
        list.stream().forEach(comment -> {
            List<String> commentPicArry = new ArrayList<>();
            if(StringUtils.isNotBlank(comment.getCommentPics())) {
                commentPicArry = Arrays.asList(comment.getCommentPics().split(","));
            }else{
                comment.setCommentPics("");
            }
            comment.setCommentPicArry(commentPicArry);
        });
        result.setContent(list);
        return Success.success(result);
    }

    /**
     * 获取商品规格
     * 【G1005】
     *
     * @param request
     * @return
     */

    @RequestMapping(value = "/getGoodSku", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id", name = "goodsId", dataType = "string", required = true),
    })
    @ApiOperation(value = "【G1007】获取商品规格", notes = "获取商品规格")
    @ApiOperationSupport(order = 7)
    public Success getGoodSku(String goodsId,String skuInfo) {
        LambdaQueryWrapper<JdGoodsSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdGoodsSku::getGoodsId,goodsId);
        List<JdGoodsSku> skuList = skuService.list(wrapper);
        System.out.println(skuList);
        if (skuList != null && skuList.size() > 0) {
            for (JdGoodsSku sku : skuList) {
                String attr = StringUtils.strip(sku.getAttrInfo(), "[]");  //去掉中括号
                JSONArray array = JSON.parseArray(sku.getAttrInfo());
                    if (array != null && array.size() > 0) {
                        List<String> att = new ArrayList<>();
                        for (int i = 0; i < array.size(); i++) {
                            JSONObject job = array.getJSONObject(i);
                            String value = job.getString("value");
                            att.add(value);
                        }
                    }

                     String s = String.join(",", attr);
                    if (s.equals(skuInfo)) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("salePrice", sku.getSkuSaleprice());
                        map.put("costprice", sku.getSkuCostprice());
                        map.put("sales", sku.getSkuSales());
                        map.put("imgUrl", sku.getSkuImgurl());
                        map.put("skuId", sku.getId());
                        JSONArray arr = JSON.parseArray(sku.getAttrInfo());
                        List<SkuVo> list = new ArrayList<>();
                        if (arr != null && arr.size() > 0) {
                            for (int i = 0; i < arr.size(); i++) {
                                SkuVo skuVo = new SkuVo();
                                JSONObject job = arr.getJSONObject(i);
                                String attrName = job.getString("name");
                                String value = job.getString("value");
                                List<String> attrValue = Collections.singletonList(value);
                                skuVo.setName(attrName);
                                skuVo.setAttr(attrValue);
                                list.add(skuVo);
                            }
                        }
                        map.put("attrList", list);
                        return Success.success(map);
                    }

            }
        }
        return Success.success();
    }

    /**
     * 运费计算
     * 【G1005】
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getFee", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品id", name = "goodsId", dataType = "string"),
            @ApiImplicitParam(value = "规格id", name = "skuId", dataType = "string"),
            @ApiImplicitParam(value = "购物车id", name = "cartIds", dataType = "string"),
            @ApiImplicitParam(value = "数量", name = "num", dataType = "string"),
            @ApiImplicitParam(value = "收货地址", name = "addressId", dataType = "string"),
    })
    @ApiOperation(value = "【G1008】运费计算", notes = "运费计算")
    @ApiOperationSupport(order = 8)
    public Success<Object> getFee(HttpServletRequest request, HttpServletResponse response) {
        String goodsId = request.getParameter("goodsId");
        String skuId = request.getParameter("skuId");
        String cartIds = request.getParameter("cartIds");
        String num = request.getParameter("num");
        String addressId = request.getParameter("addressId");
        if (StringUtils.isEmpty(goodsId) && StringUtils.isEmpty(skuId) && StringUtils.isEmpty(cartIds) && StringUtils.isEmpty(num) && StringUtils.isEmpty(addressId)) {
            return Success.error("参数为空");
        }
        return freightTemplateService.getFee(goodsId, skuId, cartIds, num, addressId);
    }




}
